package site.icesky.springboot.threadpool.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import site.icesky.springboot.threadpool.util.FileUtil;

import java.util.List;


/**
 * @ClassName: FileDeal <br>
 * @Description: 多线程并发处理 <br>
 * @Package: site.icesky.springboot.threadpool.service <br>
 * @author: suitianmou <br>
 * @Date: 2020/8/17-20:00 <br>
 * @version: 1.0 <br>
 * @see <br>
 * @since (从产品的哪一个版本此类被添加进来 ( 可选))<br>
 * 修改历史: <br>
 * 修改时间             修改人           版本变更           修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Service
@Scope("prototype") //多例
public class FileDeal implements Runnable{

    private Logger logger = LoggerFactory.getLogger(FileDeal.class);
    private String fileName;
    private int lineNum;
    private int fileStep;

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        deal();
    }

    // 文件处理
    public void deal(){
        logger.info("开始执行任务:filename[{}],startLine[{}]", fileName, lineNum);
        List<String> lines = FileUtil.readFileByLine(fileName, lineNum, fileStep);
        if( lines == null){
            logger.error("按行读取文件异常--[{}][{}]", fileName, lineNum);
            return;
        }

        for( String line : lines){
            sendMsg(line);
        }

        return;
    }

    public boolean sendMsg( String line){
        logger.info("文件中的内容为:[{}][{}]", line, Thread.currentThread().getId());
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            return true;
        }
        return true;
    }


    public int getFileStep() {
        return fileStep;
    }

    public void setFileStep(int fileStep) {
        this.fileStep = fileStep;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public int getLineNum() {
        return lineNum;
    }

    public void setLineNum(int lineNum) {
        this.lineNum = lineNum;
    }
}
